package cn.msn.filter;

import com.alibaba.fastjson.JSONObject;
import com.netflix.zuul.ZuulFilter;
import com.netflix.zuul.context.RequestContext;
import com.netflix.zuul.exception.ZuulException;
import lombok.SneakyThrows;
import org.springframework.stereotype.Component;
import org.springframework.util.StringUtils;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.PrintWriter;
import java.util.HashMap;
@Component
public class LoginFilter extends ZuulFilter {
    @Override
    public String filterType() {
        return "pre";
    }

    @Override
    public int filterOrder() {
        return 1;
    }

    @Override
    public boolean shouldFilter() {
        // 1.获取请求地址
        HttpServletRequest request = RequestContext.getCurrentContext().getRequest();
        String uri = request.getRequestURI();
        // 2.判断请求路径是否以login/register结尾，包含就不执行登录业务校验，所以返回false
        if (uri.endsWith("login") || uri.endsWith("register") ) {
            return false;
        }
        return true;
    }

    @SneakyThrows
    @Override
    public Object run(){
        // 1.获取请求的token
        RequestContext requestContext = RequestContext.getCurrentContext();
        String token = requestContext.getRequest().getHeader("token");
        HttpServletResponse response = RequestContext.getCurrentContext().getResponse();
        response.setContentType("application/json;charset=utf-8");
        // 2.判断token是否存在
        if (StringUtils.isEmpty(token)) {
                PrintWriter writer = response.getWriter();
                HashMap<String,Object> map = new HashMap<>();
                map.put("success",false);
                map.put("message","请登录");
                map.put("obj","noLogin");
                String strMap = JSONObject.toJSONString(map);
                writer.write(strMap);
                // 3.阻止过滤器后续执行
                RequestContext.getCurrentContext().setSendZuulResponse(false);
        }
        return null;
    }
}
